package com.hotfire.template.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hotfire.template.common.Constants;

public class AuthorizedUserInterceptor extends HandlerInterceptorAdapter {
	private static final Logger log = Logger.getLogger(AuthorizedUserInterceptor.class);
	/**
	 * 从配置文件中传入需要过滤的URL
	 */
	private List<String> skipUrls = new ArrayList<String>();
	
	@Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
		
		/**
		 * 过滤不需要用户登录认证的URL
		 */
		if(skipUrls.contains(request.getServletPath())) {
			return true;
		}
		if (request.getSession().getAttribute(Constants.USER_SESSION_ATTR) != null) {
            return true;
        }
		log.info("[authorizedUserInterceptor] user not login , redirect to login page . . request url : ".concat(request.getRequestURI()));
		
        String requestedWith = request.getHeader("x-requested-with");
	    if (requestedWith != null && "XMLHttpRequest".equals(requestedWith)) {
            if (log.isInfoEnabled()) {
                log.info("[authorizedUserInterceptor] This's ajax , response json data !");
            }
            response.setHeader("Authorized", "false");
            return false;
        }
	    String url= request.getContextPath().concat("/user/login?referer=").concat(request.getServletPath()) ;
	    if(request.getQueryString() != null){
	        url = url.concat("?").concat(request.getQueryString());
	    }
		
        response.sendRedirect(url);
        return false;     
    }    
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	/**
	 * @param skipUrls the skipUrls to set
	 */
	public void setSkipUrls(List<String> skipUrls) {
		this.skipUrls = skipUrls;
	}
}
